<?php
/**
 * Created by PhpStorm.
 * User: mr.houhai
 * Date: 2018/1/25
 * Time: 20:07
 */

namespace Xcx\Model;

use Xcx\Common\ErrorCode;

class SharePhotoModel extends BaseModel
{

    /**
     * 照片墙分享
     * @param $pid
     * @param $openGID
     * @return bool
     */
    public function doSharePhoto($pid, $openGID)
    {
        //判断用户是否分享过
        if ($this->checkIsShareToGroup($pid, $openGID)) return ErrorCode::$ShareToSameGroup;
        //超出分享限制
        $shareCount = $this->getShareCount($pid);
        if ($shareCount >= 10) return ErrorCode::$ShareOverLimit;

        M()->startTrans();
        //添加分享记录
        $res1 = $this->addShareRecord($pid,$openGID);
        //分享成功后，给用户添加一条有效的点赞记录
        $PraiseRecord = new PraiseRecordModel();
        $res2 = $PraiseRecord->addSharePraiseRecord($pid);

        if ($res1 && $res2) {
            M()->commit();
            return ErrorCode::$Success;
        } else {
            M()->rollback();
            return ErrorCode::$Fail;
        }
    }

    /**
     * 检查是否分享至群
     * @param $pid
     * @param $openGID
     * @return bool
     */
    private function checkIsShareToGroup($pid,$openGID)
    {
        $maps['pid'] = $pid;
        $maps['open_gid'] = $openGID;

        $startTime = strtotime(date('Ymd'));
        $endTime = strtotime(date('Ymd')) + 24 * 3600;
        $maps['add_time'] = array('BETWEEN',array($startTime,$endTime));

        $data = $this->where($maps)->find();
        if (is_array($data) && count($data) > 0) {
            return true;
        }
        return false;
    }

    private function getShareCount($pid)
    {
        $maps['pid'] = $pid;

        $startTime = strtotime(date('Ymd'));
        $endTime = strtotime(date('Ymd')) + 24 * 3600;
        $maps['add_time'] = array('BETWEEN',array($startTime,$endTime));

        return $this->where($maps)->count();
    }

    /**
     * 添加分享记录
     * @param $pid
     * @param $openGID
     * @return mixed
     */
    private function addShareRecord($pid, $openGID)
    {
        $data['uid'] = $this->uid;
        $data['pid'] = $pid;
        $data['open_gid'] = $openGID;
        $data['add_time'] = time();

        return $this->data($data)->add();
    }


}